package org.springframework.beans.factory.config;

import org.springframework.beans.factory.anno.Component;
import org.springframework.beans.factory.support.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.util.ConfigurationClassUtils;
import org.springframework.beans.factory.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/16
 */
public class ComponentScanAnnotationParser {

    private final BeanDefinitionRegistry registry;

    private BeanNameGenerator beanNameGenerator;

    public ComponentScanAnnotationParser(BeanDefinitionRegistry registry) {
        this.registry = registry;
        this.beanNameGenerator = new AnnotationBeanNameGenerator();
    }

    public Set<BeanDefinitionHolder> parse(String packageStr) {
        Set<BeanDefinitionHolder> holders = new HashSet<>();
        if(StringUtils.isBlank(packageStr))
            return holders;
        List<String> clazzStrs = ConfigurationClassUtils.basePackageScan(packageStr);
        for (String clazzStr:clazzStrs) {
            try {
                Class<?> clazz = Class.forName(clazzStr);
                if (clazz.isAnnotationPresent(Component.class)) {

                     AnnotatedBeanDefinition abd = new AnnotatedGenericBeanDefinition(clazz);

                     String beanName = this.beanNameGenerator.generateBeanName(abd);
                     if(!registry.containsBeanDefinition(beanName)){
                         this.registry.registerBeanDefinition(beanName,abd);
                         holders.add(new BeanDefinitionHolder(beanName,abd));
                     }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        return holders;
    }
}
